package com.campus.merchant.interceptor;

import com.alibaba.fastjson.JSON;
import com.campus.merchant.service.RedisService;
import com.campus.merchant.vo.UserInfoVo;
import com.campus.common.bean.common.Resp;
import com.campus.common.constants.GlobalConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Author : zhaoyujie
 * @Description : 登录拦截
 * @Date: 2019/02/15
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    @Autowired
    private RedisService redisService;
    

    /**
     * 这个方法是在访问接口之前执行的，我们只需要在这里写验证登陆状态的业务逻辑，就可以在用户调用指定接口之前验证登陆状态了.<br/>
     * 这个方法返回false表示忽略当前请求，如果一个用户调用了需要登陆才能使用的接口，如果他没有登陆这里会直接忽略掉.<br/>
     * 当然你可以利用response给用户返回一些提示信息，告诉他没登陆
     *
     * @param request
     * @param response
     * @param arg2
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            returnJson(response, JSON.toJSONString(Resp.error(GlobalConstant.ERROR_CODE_NOT_LOGIN,"Please log in and try again!")));
            return false;
        }

        UserInfoVo userInfo = redisService.getFromJson(token, UserInfoVo.class);
        
        if (userInfo != null) {
            return true;
        } else {
            returnJson(response, JSON.toJSONString(Resp.error(GlobalConstant.ERROR_CODE_NOT_LOGIN,"Please log in and try again!")));
            return false;
        }
    }


    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
    }

    public static void returnJson(HttpServletResponse response, String json) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        try {
            writer = response.getWriter();
            writer.print(json);
        } catch (Exception e) {
        } finally {
            if (writer != null)
                writer.close();
        }
    }

}
